import { createRouter, createWebHashHistory } from "vue-router";
import { useUser } from "../store/user";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      component: () => import("../views/main.vue"),
      redirect: "/home",
      children: [
        {
          path: "/home",
          component: () => import("../views/home.vue"),
        },
        {
          path: "/job",
          component: () => import("../views/job.vue"),
        },
        {
          path: "/mine",
          component: () => import("../views/mine.vue"),
        },
      ],
    },
    {
      path: "/login",
      component: () => import("../views/login.vue"),
    },
    {
      path: "/edit",
      component: () => import("../views/edit.vue"),
    },
    {
      path: "/detail/:id",
      component: () => import("../views/detail.vue"),
    },
    {
      path: "/test/pinia",
      component: () => import("../views/test-pinia/index.vue"),
    },
  ],
});

router.beforeEach((to, _, next) => {
  let blackList = ["/mine"];
  if (blackList.includes(to.path)) {
    const user = useUser(); //调用位置很重要
    if (user.userInfo) {
      next();
    } else {
      next("/login");
    }
  } else {
    next(); //不是黑名单路由，直接放行
  }
});

export default router;
